package org.example.controller;

import org.example.config.ThirdAppConfig;
import org.example.config.ThirdAppTypeItemVo;
import org.example.service.ThirdAppWechatEnterpriseService;
import org.example.util.JwtUtil;
import org.example.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


@RestController
@RequestMapping("/sys/thirdLogin")
public class ThirdLoginController {

    @Autowired
    ThirdAppConfig thirdAppConfig;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ThirdAppWechatEnterpriseService thirdAppWechatEnterpriseService;

    @Value("${appUrl}")
    private String appUrl;


    @GetMapping("/hello")
     String ow(HttpServletRequest request){
        System.out.println(request.getContentType());
        return "HELLO";
    }


    @GetMapping("/test")
    public  String test(){
        redisUtil.set("name","zhangfei");
        return "ok";
    }

    @GetMapping("/test1")
    public  String test1(){
        return (String) redisUtil.get("name");
    }


    /**
     * 企业微信/钉钉 OAuth2登录
     *
     * @param source
     * @param state
     * @return
     */
    @ResponseBody
    @GetMapping("/oauth2/{source}/login")
    public String oauth2LoginCallback(@PathVariable("source") String source, @RequestParam("state") String state, HttpServletResponse response) throws Exception {
        String url;
        if (ThirdAppConfig.WECHAT_ENTERPRISE.equalsIgnoreCase(source)) {
            ThirdAppTypeItemVo config = thirdAppConfig.getWechatEnterprise();
            StringBuilder builder = new StringBuilder();
            // 构造企业微信OAuth2登录授权地址
            builder.append("https://open.weixin.qq.com/connect/oauth2/authorize");
            // 企业的CorpID
            builder.append("?appid=").append(config.getClientId());
            // 授权后重定向的回调链接地址，请使用urlencode对链接进行处理
            String redirectUri = thirdAppConfig.getRedirectUrl();
            builder.append("&redirect_uri=").append(URLEncoder.encode(redirectUri, "UTF-8"));
            // 返回类型，此时固定为：code
            builder.append("&response_type=code");
            // 应用授权作用域。
            // snsapi_base：静默授权，可获取成员的的基础信息（UserId与DeviceId）；
            builder.append("&scope=snsapi_base");
            // 重定向后会带上state参数，长度不可超过128个字节
            builder.append("&state=").append(state);
            // 终端使用此参数判断是否需要带上身份信息
            builder.append("#wechat_redirect");
            url = builder.toString();
        } else {
            return "不支持的source";
        }
        response.sendRedirect(url);
        return "login…";
    }

    /**
     * 企业微信/钉钉 OAuth2登录回调
     *
     * @param code
     * @param state
     * @param response
     * @return
     */
    @ResponseBody
    @GetMapping("/oauth2/{source}/callback")
    public String oauth2LoginCallback(
            @PathVariable("source") String source,
            // 企业微信返回的code
            @RequestParam(value = "code", required = false) String code,
            // 钉钉返回的code
            @RequestParam(value = "authCode", required = false) String authCode,
            @RequestParam("state") String state,
            HttpServletResponse response
    ) {
        String  loginUser;
        if (ThirdAppConfig.WECHAT_ENTERPRISE.equalsIgnoreCase(source)) {
            loginUser = thirdAppWechatEnterpriseService.oauth2Login(code);
            if (loginUser == null) {
                return "登录失败";
            }
        } else {
            return "不支持的source";
        }
        try {
            String token = saveToken(loginUser);
            state += appUrl + URLEncoder.encode(token, "UTF-8");
            state += "&thirdType=" + "wechat_enterprise";
            try {
                response.sendRedirect(state);
                return "ok";
            } catch (IOException e) {
                e.printStackTrace();
                return "重定向失败";
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "解码失败";
        }
    }

    private String saveToken(String username) {
        // 生成token
        String token = JwtUtil.sign(username, "123456");
        redisUtil.set("prefix_user_token_" + token, token);
        // 设置超时时间
        redisUtil.expire("prefix_user_token_" + token, JwtUtil.EXPIRE_TIME / 1000);
        return token;
    }





}
